package com.example.lib.utils.thread;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPool {
    //如果是CPU密集型应用，则线程池大小设置为N+1
    //如果是IO密集型应用，则线程池大小设置为2N+1
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    //核心线程数量大小
    private static final int corePoolSize = Math.max(2, Math.min(CPU_COUNT - 1, 4));//核心线程池数量
    private final int maximumPoolSize = CPU_COUNT * 2 + 1;//线程池的最大线程数量
    private final int keepAliveTime = 1;//线程在没有任务执行之后多久销毁 单位：分钟
    private final ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.MINUTES, new LinkedBlockingDeque<>(), new ThreadPoolExecutor.DiscardPolicy());

    private static volatile ThreadPool instance;

    public static ThreadPool getInstance() {
        if (instance == null) {
            synchronized (ThreadPool.class) {
                if (instance == null) {
                    instance = new ThreadPool();
                }
            }
        }
        return instance;
    }

    public void execute(Runnable runnable) {
        executor.execute(runnable);
    }

    public void close() {
        executor.shutdown();
    }
}
